<template>
    <div class="content">
        <vxe-grid ref="xGrid" v-bind="gridOptions" @checkbox-change="handleSelectionChange" @edit-actived="editActivedEvent" :data="ruleData">
            <template #toolbar_buttons>
                <el-row :gutter="10">
                    <el-col :span="1.5">
                        <el-button type="info" plain icon="Plus" @click="handleAdd">新增</el-button>
                    </el-col>
                    <el-col :span="1.5">
                        <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete">删除</el-button>
                    </el-col>
                </el-row>
            </template>
            <template #slotRequired="{ row }">
                <vxe-switch v-model="row['ignore']" size="medium" open-value="1" close-value="0"></vxe-switch>
            </template>
        </vxe-grid>
    </div>
</template>

<script setup lang="ts">
    import { ref, reactive, getCurrentInstance } from "vue";
    import { VxeGridInstance, VxeGridProps, VxeGridEvents, GridMethods, TableMethods, TableEditMethods, TableValidatorMethods } from "../../../../../types/index";
    import useBaseApi from "@/api/base/index";
    import { gridComponentMethodKeys } from "@/components/ElementRender/src/methods";
    import XEUtils from "xe-utils";
    const { proxy } = getCurrentInstance() as any;
    const { callRemoves } = useBaseApi("/tableConfig/tableRules");
    const tableHeight = ref(document.documentElement.scrollHeight - 239 + "px");
    const xGrid = ref({} as VxeGridInstance);
    const multiple = ref(true);
    const props = defineProps({
        ruleData: {
            type: Array,
        },
    });
    console.log("校验规则配置", props.ruleData);
    const gridOptions = reactive<VxeGridProps>({
        border: true,
        resizable: true,
        showHeaderOverflow: true,
        showOverflow: true,
        highlightHoverRow: true,
        keepSource: true,
        id: "170",
        height: tableHeight,
        sortConfig: {
            trigger: "cell",
            remote: true,
        },
        filterConfig: {
            remote: true,
        },
        pagerConfig: {
            pageSize: 10,
            pageSizes: [5, 10, 15, 20, 50, 100, 200, 500, 1000],
            perfect: true,
            enabled: false,
        },
        toolbarConfig: {
            refresh: true,
            zoom: true,
            custom: true,
            slots: {
                buttons: "toolbar_buttons",
            },
        },
        // proxyConfig: {
        //     paramsChangeLoad: false, //额外的请求参数改变时是否重新请求数据
        //     seq: false, // 启用动态序号代理，每一页的序号会根据当前页数变化
        //     sort: true, // 启用排序代理，当点击排序时会自动触发 query 行为
        //     filter: true, // 启用筛选代理，当点击筛选时会自动触发 query 行为
        //     form: false, // 启用表单代理，当点击表单提交按钮时会自动触发 reload 行为
        //     // 对应响应结果 { result: [], page: { total: 100 } }
        //     props: {
        //         result: "rows", // 配置响应结果列表字段
        //         total: "total", // 配置响应结果总页数字段
        //     },
        //     ajax: {
        //         // 接收 Promise
        //         query: ({ page, sorts, filters, form, params }: any) => {
        //             const queryParams: any = Object.assign({}, form);
          //// 处理排序条件
        //  const orderByColumn = <Array<String>>[];
        //         const isAsc = <Array<Boolean>>[];
        //         sorts.forEach((m: any) => {
        //             orderByColumn.push(m.field);
        //             isAsc.push(m.order);
        //         });
        //         queryParams.orderByColumn = orderByColumn.join(",");
        //         queryParams.isAsc = isAsc.join(",");
        //             // 处理筛选条件
        //             filters.forEach(({ property, values }: any) => {
        //                 queryParams[property] = values.join(",");
        //             });
        //             return callList({
        //                 page: {
        //                     current: page.currentPage,
        //                     size: page.pageSize,
        //                 },
        //                 ...queryParams,
        //                 ...params,
        //                 tableId: 0,
        //             }).then((response: any) => {
        //                 return response?.rows;
        //             });
        //         },
        //         delete: async ({ body }: any) => {
        //             await callRemoves(body.removeRecords.map((item: any) => item.columnId));
        //         },
        //     },
        // },
        columns: [
            { type: "checkbox", width: 50 },
            {
                field: "editRulesId",
                title: "序号",
                width: 80,
            },
            {
                field: "field",
                title: "字段",
                width: 140,
                editRender: {
                    name: "input",
                    attrs: { placeholder: "请输入字段名" },
                },
            },
            {
                field: "required",
                title: "是否必填",
                width: 155,
                editRender: {
                    name: "$switch",
                    props: {
                        openValue: 1,
                        closeValue: 0,
                    },
                },
                slots: {
                    default: "slotRequired",
                },
            },
            {
                field: "min",
                title: "校验值最小长度",
                width: 140,
                editRender: {
                    name: "input",
                    attrs: { placeholder: "请输入" },
                },
            },
            {
                field: "max",
                title: "校验值最大长度",
                width: 140,
                editRender: {
                    name: "input",
                    attrs: { placeholder: "请输入" },
                },
            },
            {
                field: "type",
                title: "数据校验的类型",
                width: 140,
                editRender: {
                    name: "select",
                    options: [
                        {
                            value: "string",
                            label: "string",
                        },
                        {
                            value: "number",
                            label: "number",
                        },
                        {
                            value: "array",
                            label: "array",
                        },
                    ],
                },
            },
            {
                field: "pattern",
                title: "正则校验",
                width: 140,
                editRender: {
                    name: "input",
                    attrs: { placeholder: "请输入" },
                },
            },
            {
                field: "message",
                title: "校验提示内容",
                width: 140,
                editRender: {
                    name: "input",
                    attrs: { placeholder: "请输入" },
                },
            },
            {
                field: "trigger",
                title: "触发校验方式",
                width: 130,
                editRender: {
                    name: "select",
                    options: [
                        {
                            value: "blur",
                            label: "blur",
                        },
                        {
                            value: "change",
                            label: "change",
                        },
                        {
                            value: "manual",
                            label: "manual",
                        },
                    ],
                },
            },
            {
                field: "validator",
                title: "自定义校验方法",
                width: 160,
                titlePrefix: { message: "返回一个 Error 或者 Promise<new Error('提示消息')>" },
                editRender: { name: "MonacoEditor", attrs: { placeholder: "请输入" }, props: { title: "自定义校验方法" } },
            },
            {
                field: "remark",
                title: "备注",
                width: 120,
                editRender: { name: "input", attrs: { placeholder: "请输入备注" } },
            },
        ],
        editConfig: {
            trigger: "click",
            mode: "row",
            showStatus: true,
        },
        editRules: {
            field: [{ required: true, message: "字段必须填写" }],
        },
    });
    const disabledField = ref(false);
    const editActivedEvent: VxeGridEvents.EditDisabled = ({ row }) => {
        disabledField.value = null != row["field"];
    };
    /** 多选框选中数据 */
    function handleSelectionChange(data: any) {
        multiple.value = !data.records.length;
    }
    /**新增 */
    function handleAdd() {
        xGrid.value.commitProxy("insert").then(({ row }: any) => {
            row["editRulesId"] = null;
            row["required"] = 1;
            xGrid.value.setEditRow(row);
        });
    }
    /**删除 */
    async function handleDelete() {
        const { rows } = await xGrid.value.removeCheckboxRow();
        const deleteIds = ref([]);
        XEUtils.arrayEach(rows, (item: any) => {
            if (item["editRulesId"]) {
                deleteIds.value.push(item["editRulesId"]);
            }
        });
        if (deleteIds.value.length > 0) {
            callRemoves(deleteIds.value.join(","));
        }
    }
    /**获取数据 */
    function getRoleData() {
        return [...xGrid.value.getTableData().tableData];
    }
    const extendTableMethods = (methodKeys: any) => {
        const funcs: any = {};
        methodKeys.forEach((name: any) => {
            funcs[name] = (...args: any[]) => {
                const $vxegrid: any = xGrid.value;
                if ($vxegrid && $vxegrid[name]) {
                    return $vxegrid[name](...args);
                }
            };
        });
        return funcs;
    };

    const gridExtendTableMethods = extendTableMethods(gridComponentMethodKeys) as GridMethods & TableMethods & TableEditMethods & TableValidatorMethods;
    defineExpose({
        ...gridExtendTableMethods,
        getRoleData,
    });
</script>
<style scoped>
    .content {
        padding: 10px;
        box-shadow: var(--el-box-shadow-light);
        border-radius: var(--el-card-border-radius);
        border: 1px solid var(--el-card-border-color);
        background-color: var(--el-card-bg-color);
        overflow: hidden;
        color: var(--el-text-color-primary);
        transition: var(--el-transition-duration);
    }
</style>
